package it.netsphere.nswing.comp;


import java.awt.Toolkit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.*;
import javax.swing.text.*;

public class NSTextFieldRegExp extends JTextField
{
	private static final long serialVersionUID = 5541208668848898981L;

	public NSTextFieldRegExp()
	{
	} 

	private String regExp;
	public String getRegExp(){return regExp;}
	public void setRegExp(String regExp){this.regExp = regExp; pattern=null; }
	
	private Pattern pattern;
	private Pattern getPattern()
	{
		if( pattern ==null && getRegExp()!=null )
		{
			pattern = Pattern.compile( getRegExp() );
		}
		
		return pattern;
	}
	
	
	/**
	 * Create a new document model for this control that only accepts integral
	 * values.
	 * 
	 * @return The new document model.
	 */
	@Override
	protected Document createDefaultModel()
	{
		return new RegExpDocument();
	}

	/**
	 * This document only allows integral values to be added to it.
	 */
	private class RegExpDocument extends PlainDocument
	{
		private static final long serialVersionUID = 3405892854619203816L;

		@Override
		public void insertString(int offs, String str, AttributeSet a)
				throws BadLocationException
		{
			
			if(getPattern()==null)
			{
				super.insertString(offs, str, a);
				return;
			}
			
			try
			{
				String s = NSTextFieldRegExp.this.getText();
				if(s==null)
					s  = str;
				else
					s = ( offs>0 ? s.substring( 0,offs ) : "" ) + str + ( s.substring(offs) );
				
				Matcher m = getPattern().matcher( s );
				if(m.matches())
					super.insertString(offs, str, a);
			}
			catch (NumberFormatException ex)
			{
				Toolkit.getDefaultToolkit().beep();
			}
		}
	}


}
